package com.blog.realm;

import com.blog.dao.dao.UserDAO;
import com.blog.dao.domain.UserDO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Collections;


/**
 * 负责认证授权
 * @author 泡面ing
 */

public class MyRealm extends AuthorizingRealm{

    private UserDAO userDAO;
    @Autowired
    public void setUserDAO(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    /**
     * 做得到身份验证信息
     *
     * @param authenticationToken 身份验证令牌
     * @return {@link AuthenticationInfo}
     * @throws AuthenticationException 身份验证异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        token.setRememberMe(true);
        String username = token.getUsername();
        char[] password = token.getPassword();
        UserDO userDO = userDAO.get(username);
        //返回null，认证失败，抛出异常
        if (userDO == null){
            return null;
        }

        //判断密码是否一致
        if (userDO.getPassword().equals(Arrays.toString(password))){
            return null;
        }

        return new SimpleAuthenticationInfo(userDO.getUserName(), userDO.getPassword(), getName());

    }

    /**
     * 得到的授权信息
     *
     * @param principalCollection 主要收集
     * @return {@link AuthorizationInfo}
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //获取一个可用的身份，取决于SimpleAuthenticationInfo中的封装的信息;
        String username = super.getAvailablePrincipal(principalCollection).toString();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        UserDO userDO = userDAO.get(username);

        final String jurId = userDO.getJurId();

        final String disable = userDO.getDisable().toString();

        //给某个人分配权限
        info.addStringPermissions(Collections.singleton(jurId));
        //是否是禁用角色
        info.addRoles(Collections.singleton(disable));
        return info;
    }

}
